package org.edu.modules.stu.stu.controller;

import com.alibaba.fastjson.support.geo.LineString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.edu.common.base.ConditionDto;
import org.edu.common.dto.ExcelPo;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.common.utils.PoiUtils;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.entity.VeBaseSemester;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.edu.modules.stu.common.service.VeBaseSemesterService;
import org.edu.modules.stu.common.service.VeBaseTeacherService;
import org.edu.modules.stu.stu.dto.VeStuCheckDto;
import org.edu.common.dto.AllDto;
import org.edu.modules.stu.stu.entity.StuCheck;
import org.edu.modules.stu.stu.entity.VeStuCheck;
import org.edu.modules.stu.stu.service.StuCheckService;
import org.edu.modules.stu.stu.service.VeStuCheckService;
import org.edu.common.api.vo.Result;
import org.edu.common.base.PageDto;
import org.edu.common.dto.StatusDto;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.edu.modules.stu.stu.vo.ExportstuCheckVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import static org.apache.poi.hssf.record.ExtendedFormatRecord.THIN;


@Api(tags = {"考勤信息表"})
@RestController
@RequestMapping("/stu/veStuCheck")
@Slf4j
public class VeStuCheckController {

    @Autowired
    private VeStuCheckService veStuCheckService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Autowired
    private VeBaseTeacherService veBaseTeacherService;

    @Autowired
    private VeBaseSemesterService veBaseSemesterService;


    @Autowired
    private StuCheckService stuCheckService;


    @ApiOperation("分页查询考勤信息表")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageDto<VeStuCheck> page) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        IPage<VeStuCheckDto> pageDto = null;
        QueryWrapper<VeStuCheck> queryWrapper = page.buildQueryWrapper(VeStuCheck.class);
        if (appUser.getUserType().contains("2")) {
            //如果用户类型是2，为学生账号
            pageDto = veStuCheckService.pageDtoByUserId(page, queryWrapper, appUser.getUserId());
            return Result.OK(pageDto);
        } else if (appUser.getUserType().contains("1")) {
            //如果用户类型是1，为教师账号
            List<Integer> studentIdsList = veBaseTeacherService.getStudentIdsListBySysUserId(appUser.getUserId());

            queryWrapper.in("stu_id", studentIdsList);
            pageDto = veStuCheckService.pageDto(page, queryWrapper);
            return Result.OK(pageDto);
        } else {
            pageDto = veStuCheckService.pageDto(page, queryWrapper);
        }
        return Result.OK(pageDto);
    }

    /**
     * 查询所有
     */
    @ApiOperation("查询所有")
    @PostMapping("/all")
    public Result<?> all(@RequestBody AllDto<VeStuCheck> page) {
        QueryWrapper<VeStuCheck> queryWrapper = page.buildQueryWrapper(VeStuCheck.class);
        List<VeStuCheck> list = veStuCheckService.listByWrapper(queryWrapper);
        return Result.OK(list);
    }

    @ApiOperation("导出数据）")
    @PostMapping("/export")
    public Result<?> export(@RequestBody PageDto<VeStuCheck> page, HttpServletResponse resp) {
        QueryWrapper<VeStuCheck> queryWrapper = page.buildQueryWrapper(VeStuCheck.class);
        List<ExcelPo> list = new ArrayList<>();
        list.add(new ExcelPo("学生姓名", "name"));
        list.add(new ExcelPo("学生学号", "code"));
        list.add(new ExcelPo("班级名称", "bjText"));
        list.add(new ExcelPo("考勤类型", "typeName"));
        list.add(new ExcelPo("考勤名称", "courseName"));
        list.add(new ExcelPo("异常时间", "checkTime"));
        list.add(new ExcelPo("备注", "content"));
        PoiUtils.downloadFile(resp, veStuCheckService.pageDto(page, queryWrapper).getRecords(), list);
        return Result.OK();
    }

    @AutoLog(value = "考勤信息表-分页列表查询")
    @ApiOperation(value = "考勤信息表-分页列表查询", notes = "考勤信息表-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(VeStuCheck entity,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeStuCheck> queryWrapper = QueryGenerator.initQueryWrapper(entity, req.getParameterMap());
        PageDto<VeStuCheck> page = new PageDto<VeStuCheck>(pageNo, pageSize);
        IPage<VeStuCheck> pageList = veStuCheckService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeStuCheck dto = veStuCheckService.findDtoById(id);
        if (dto == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dto);
    }

    @AutoLog(value = "添加")
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeStuCheckDto dto) {
        veStuCheckService.insertOrUpdate(dto, true);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeStuCheckDto dto) {
        veStuCheckService.insertOrUpdate(dto, false);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        veStuCheckService.delete(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "更新状态")
    @ApiOperation(value = "更新状态")
    @PostMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody StatusDto statusDto) {
        UpdateWrapper<VeStuCheck> updateWrapper = new UpdateWrapper<>();
        if (statusDto.getIds() != null && statusDto.getIds().size() > 0) {
            updateWrapper.set("status", statusDto.getStatus());
            updateWrapper.in("id", statusDto.getIds());
            veStuCheckService.update(updateWrapper);
            return Result.OK("批量更新成功!");
        } else {
            return Result.error("未选择!");
        }
    }


    @AutoLog(value = "分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @GetMapping(value = "/selectStuChecklistOld")
    public ModelAndView selectStuChecklist(@RequestParam("week") String week,
                                           @RequestParam("specId") String specId,
                                           @RequestParam("bjId") String bjId,
                                           @RequestParam("gradeId") String gradeId,
                                           @RequestParam("falId") String falId,
                                           HttpServletRequest req) {

        StuCheck stuCheck = new StuCheck();
        stuCheck.setBjId(bjId);
        stuCheck.setFalId(falId);
        stuCheck.setWeek(week);
        stuCheck.setGradeId(gradeId);
        stuCheck.setSpecId(specId);
        List<Map<String, String>> list = stuCheckService.selectStuChecklist(stuCheck);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "考勤信息管理");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, ExportstuCheckVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("考勤信息管理", "导出人:" + user.getRealname(), "导出考勤信息管理列表");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    @AutoLog(value = "考勤列表查询")
    @ApiOperation(value = "考勤列表查询", notes = "考勤列表查询")
    @PostMapping(value = "/selectStuChecklist")
    public ResponseEntity<byte[]> ws(@RequestBody PageDto<VeStuCheck> page) {
        String week = "";
        String specId = "";
        String bjId = "";
        String gradeId = "";
        String falId = "";
        String semId = "";
        //获取参数
        ListIterator<ConditionDto> iterator = page.getConditions().listIterator();
        while (iterator.hasNext()) {
            int currentIndex = iterator.nextIndex();
            // 获取当前行（元素）
            ConditionDto currentCondition = iterator.next();
            // 处理当前元素
            if (page.getConditions().get(currentIndex).getColumn().equals("week") == true) {
                week = currentCondition.getValue().toString();
            } else if (page.getConditions().get(currentIndex).getColumn().equals("spec_id") == true) {
                specId = currentCondition.getValue().toString();
            } else if (page.getConditions().get(currentIndex).getColumn().equals("bj_id") == true) {
                bjId = currentCondition.getValue().toString();
            } else if (page.getConditions().get(currentIndex).getColumn().equals("grade_id") == true) {
                gradeId = currentCondition.getValue().toString();
            } else if (page.getConditions().get(currentIndex).getColumn().equals("fal_id") == true) {
                falId = currentCondition.getValue().toString();
            } else if (page.getConditions().get(currentIndex).getColumn().equals("sem_id") == true) {
                semId = currentCondition.getValue().toString();
            }
        }

        /*if (StringUtils.isEmpty(week) | StringUtils.isEmpty(specId) | StringUtils.isEmpty(bjId) | StringUtils.isEmpty(gradeId) | StringUtils.isEmpty(falId)) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }*/
        StuCheck stuCheck = new StuCheck();
        stuCheck.setBjId(bjId);
        stuCheck.setFalId(falId);
        stuCheck.setWeek(week);
        stuCheck.setGradeId(gradeId);
        stuCheck.setSpecId(specId);
        //如果没有传学期，查当前学期 lei
        if (semId.equals("")) {
            VeBaseSemester currentSemester = veBaseSemesterService.getCurrentSemester();
            semId = currentSemester.getId().toString();
            stuCheck.setSemId(semId);
        }

        List<Map<String, String>> list = stuCheckService.selectStuChecklist(stuCheck);
        try (Workbook workbook = new XSSFWorkbook();) {
            // 创建Sheet1并填充数据
            Sheet sheet1 = workbook.createSheet("Sheet1");

            // 创建第一行（标题行）
            Row headerRow0 = sheet1.createRow(0);
            //根据学期id查学期信息
            VeBaseSemester veBaseSemester = veBaseSemesterService.findById(semId);

            Row titleRow = sheet1.createRow(0);
            sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 66));
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue(veBaseSemester.getXqm() + " " +
                    veBaseSemester.getXqmc() + " 第" + week + "周 考勤表"); //  这个位置添加  表头标题 自己设置
            // 设置标题单元格样式，使其居中
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            titleCell.setCellStyle(titleStyle);


            // 创建第二行（标题行）
            Row headerRow1 = sheet1.createRow(1);
            headerRow1.createCell(0).setCellValue("序号");
            headerRow1.createCell(1).setCellValue("姓名");

            // 合并星期一区域（C到N列）
            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 2, 13));
            Cell mondayCell = headerRow1.createCell(2);
            mondayCell.setCellValue("星期一");

            // 合并星期二区域（O到Z列）
            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 14, 25));
            Cell tuesdayCell = headerRow1.createCell(14);
            tuesdayCell.setCellValue("星期二");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 26, 37));
            Cell threeCell = headerRow1.createCell(26);
            threeCell.setCellValue("星期三");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 38, 49));
            Cell fourCell = headerRow1.createCell(38);
            fourCell.setCellValue("星期四");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 50, 61));
            Cell friCell = headerRow1.createCell(50);
            friCell.setCellValue("星期五");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 62, 66));
            Cell weekCell = headerRow1.createCell(62);
            weekCell.setCellValue("周统计");
            // 创建第三行（时间段）
            Row headerRow2 = sheet1.createRow(2);
            // 填充星期一的时间段（C-N列）
            for (int i = 2; i <= 13; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 2 < 9) {
                    cell.setCellValue(i - 1); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }
            // 填充星期二的时间段（O-Z列）
            for (int i = 14; i <= 25; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 14 < 9) {
                    cell.setCellValue(i - 13); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }

            for (int i = 26; i <= 37; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 26 < 9) {
                    cell.setCellValue(i - 25); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }
            for (int i = 38; i <= 49; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 38 < 9) {
                    cell.setCellValue(i - 37); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }
            for (int i = 50; i <= 61; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 50 < 9) {
                    cell.setCellValue(i - 49); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }
            for (int i = 62; i < 67; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 62 == 0) {
                    cell.setCellValue("事假"); // v
                } else if (i - 62 == 1) {
                    cell.setCellValue("病假"); //
                } else if (i - 62 == 2) {
                    cell.setCellValue("早退"); //
                } else if (i - 62 == 3) {
                    cell.setCellValue("旷课"); //  迟到
                } else {
                    cell.setCellValue("迟到");
                }
            }

            //数据
            for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) {
                Row dataRow = sheet1.createRow(rowIndex + 3);
                Map<String, String> data = list.get(rowIndex);

                // 填充序号和姓名
                dataRow.createCell(0).setCellValue((String.valueOf(data.get("num"))));
                dataRow.createCell(1).setCellValue(data.get("name"));

                // 填充星期一到星期五的数据
                int colIndex = 2;
                for (int day = 1; day <= 5; day++) {
                    String dayName = "";
                    switch (day) {
                        case 1:
                            dayName = "day1";
                            break;
                        case 2:
                            dayName = "day2";
                            break;
                        case 3:
                            dayName = "day3";
                            break;
                        case 4:
                            dayName = "day4";
                            break;
                        case 5:
                            dayName = "day5";
                            break;
                    }
                    for (int section = 1; section <= 12; section++) {
                        dataRow.createCell(colIndex).setCellValue(data.get(dayName + "_section" + section + "_type"));
                        colIndex++;
                    }
                }

                // 填充周统计数据
                dataRow.createCell(colIndex).setCellValue(String.valueOf(data.get("count1")));
                dataRow.createCell(colIndex + 1).setCellValue(String.valueOf(data.get("count2")));
                dataRow.createCell(colIndex + 2).setCellValue(String.valueOf(data.get("count3")));
                dataRow.createCell(colIndex + 3).setCellValue(String.valueOf(data.get("count4")));
                dataRow.createCell(colIndex + 4).setCellValue(String.valueOf(data.get("count5")));
            }


            // 创建空Sheet2和Sheet3
            workbook.createSheet("Sheet2");
            workbook.createSheet("Sheet3");

            // 设置单元格样式：边框和字体居中
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);

            // 应用样式到表头
            for (int i = 0; i < 67; i++) {
                Cell cell0 = titleRow.getCell(i);
                if (cell0 != null) {
                    cell0.setCellStyle(style);
                }else {
                    titleRow.createCell(i).setCellStyle(style);
                }
                Cell cell1 = headerRow1.getCell(i);
                if (cell1 != null) {
                    cell1.setCellStyle(style);
                }else {
                    headerRow1.createCell(i).setCellStyle(style);
                }
                Cell cell2 = headerRow2.getCell(i);
                if (cell2 != null) {
                    cell2.setCellStyle(style);
                }else {
                    headerRow2.createCell(i).setCellStyle(style);
                }
            }

            // 应用样式到数据行
            for (int rowIndex = 3; rowIndex < list.size() + 3; rowIndex++) {
                Row row = sheet1.getRow(rowIndex);
                if (row != null) {
                    for (int colIndex = 0; colIndex < 67; colIndex++) {
                        Cell cell = row.getCell(colIndex);
                        if (cell == null) {
                            row.createCell(colIndex);
                            cell = row.getCell(colIndex);
                        }
                        cell.setCellStyle(style);
                    }
                }
            }

            // 写入文件
            //        try (FileOutputStream outputStream = new FileOutputStream("导出表格.xlsx")) {
            //            workbook.write(outputStream);
            //        }

            // 将工作簿写入字节数组输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            byte[] excelBytes = bos.toByteArray();

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "导出表格.xlsx");

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
//        workbook.close();
//            System.out.println("Excel file has been created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @AutoLog(value = "考勤列表查询")
    @ApiOperation(value = "考勤列表查询", notes = "考勤列表查询")
    @PostMapping(value = "/selectStuChecklist1")
    public ResponseEntity<byte[]> ws(@RequestParam("week") String week,
                                     @RequestParam("specId") String specId,
                                     @RequestParam("bjId") String bjId,
                                     @RequestParam("gradeId") String gradeId,
                                     @RequestParam("falId") String falId,
                                     HttpServletRequest req){

        if(StringUtils.isEmpty(week)|StringUtils.isEmpty(specId)|StringUtils.isEmpty(bjId)|StringUtils.isEmpty(gradeId)|StringUtils.isEmpty(falId)){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        StuCheck stuCheck=new StuCheck();
        stuCheck.setBjId(bjId);
        stuCheck.setFalId(falId);
        stuCheck.setWeek(week);
        stuCheck.setGradeId(gradeId);
        stuCheck.setSpecId(specId);
        List<Map<String, String>> list = stuCheckService.selectStuChecklist(stuCheck);
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建Sheet1并填充数据
            Sheet sheet1 = workbook.createSheet("Sheet1");

            Row titleRow = sheet1.createRow(0);
            sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 67));
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue("测试标题"); //  这个位置添加  表头标题 自己设置
            // 设置标题单元格样式，使其居中
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            titleCell.setCellStyle(titleStyle);

            // 创建表头，整体下移一行
            Row headerRow1 = sheet1.createRow(1);
            headerRow1.createCell(0).setCellValue("序号");
            headerRow1.createCell(1).setCellValue("姓名");

            // 合并星期一区域（C到N列）
            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 2, 13));
            Cell mondayCell = headerRow1.createCell(2);
            mondayCell.setCellValue("星期一");

            // 合并星期二区域（O到Z列）
            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 14, 25));
            Cell tuesdayCell = headerRow1.createCell(14);
            tuesdayCell.setCellValue("星期二");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 26, 37));
            Cell threeCell = headerRow1.createCell(26);
            threeCell.setCellValue("星期三");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 38, 49));
            Cell fourCell = headerRow1.createCell(38);
            fourCell.setCellValue("星期四");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 50, 61));
            Cell friCell = headerRow1.createCell(50);
            friCell.setCellValue("星期五");

            sheet1.addMergedRegion(new CellRangeAddress(1, 1, 62, 67));
            Cell weekCell = headerRow1.createCell(62);
            weekCell.setCellValue("周统计");

            // 创建第二行（时间段），下移一行
            Row headerRow2 = sheet1.createRow(2);
            // 填充星期一的时间段（C-N列）
            for (int i = 2; i <= 13; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 2 < 9) {
                    cell.setCellValue(i - 1); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }
            // 填充星期二的时间段（O-Z列）
            for (int i = 14; i <= 25; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 14 < 9) {
                    cell.setCellValue(i - 13); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }

            for (int i = 26; i <= 37; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 26 < 9) {
                    cell.setCellValue(i - 25); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }

            for (int i = 38; i <= 49; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 38 < 9) {
                    cell.setCellValue(i - 37); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }

            for (int i = 50; i <= 61; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 50 < 9) {
                    cell.setCellValue(i - 49); // 1-9
                } else {
                    cell.setCellValue("晚"); // 最后3列为"晚"
                }
            }

            for (int i = 62; i < 67; i++) {
                Cell cell = headerRow2.createCell(i);
                if (i - 62 == 0) {
                    cell.setCellValue("事假");
                } else if (i - 62 == 1) {
                    cell.setCellValue("病假");
                } else if (i - 62 == 2) {
                    cell.setCellValue("早退");
                } else if (i - 62 == 3) {
                    cell.setCellValue("旷课");
                } else {
                    cell.setCellValue("迟到");
                }
            }

            // 数据填充，下移一行
            for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) {
                Row dataRow = sheet1.createRow(rowIndex + 3);
                Map<String, String> data = list.get(rowIndex);

                // 填充序号和姓名
                dataRow.createCell(0).setCellValue(String.valueOf(data.get("num")));
                dataRow.createCell(1).setCellValue(data.get("name"));

                // 填充星期一到星期五的数据
                int colIndex = 2;
                for (int day = 1; day <= 5; day++) {
                    String dayName = "";
                    switch (day) {
                        case 1:
                            dayName = "day1";
                            break;
                        case 2:
                            dayName = "day2";
                            break;
                        case 3:
                            dayName = "day3";
                            break;
                        case 4:
                            dayName = "day4";
                            break;
                        case 5:
                            dayName = "day5";
                            break;
                    }
                    for (int section = 1; section <= 12; section++) {
                        dataRow.createCell(colIndex).setCellValue(data.get(dayName + "_section" + section + "_type"));
                        colIndex++;
                    }
                }

                // 填充周统计数据
                dataRow.createCell(colIndex).setCellValue(String.valueOf(data.get("count1")));
                dataRow.createCell(colIndex + 1).setCellValue(String.valueOf(data.get("count2")));
                dataRow.createCell(colIndex + 2).setCellValue(String.valueOf(data.get("count3")));
                dataRow.createCell(colIndex + 3).setCellValue(String.valueOf(data.get("count4")));
                dataRow.createCell(colIndex + 4).setCellValue(String.valueOf(data.get("count5")));
            }

            // 创建空Sheet2和Sheet3
            workbook.createSheet("Sheet2");
            workbook.createSheet("Sheet3");

            // 设置单元格样式：边框和字体居中
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);

            // 应用样式到表头
            for (int i = 0; i < 68; i++) {
                Cell cell1 = headerRow1.getCell(i);
                if (cell1 != null) {
                    cell1.setCellStyle(style);
                }
                Cell cell2 = headerRow2.getCell(i);
                if (cell2 != null) {
                    cell2.setCellStyle(style);
                }
            }

            // 应用样式到数据行
            for (int rowIndex = 3; rowIndex < list.size() + 3; rowIndex++) {
                Row row = sheet1.getRow(rowIndex);
                if (row != null) {
                    for (int colIndex = 0; colIndex < 68; colIndex++) {
                        Cell cell = row.getCell(colIndex);
                        if (cell == null) {
                            row.createCell(colIndex);
                            cell = row.getCell(colIndex);
                        }
                        cell.setCellStyle(style);
                    }
                }
            }

            // 将工作簿写入字节数组输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            byte[] excelBytes = bos.toByteArray();

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "导出表格.xlsx");

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @PostMapping("/stuCheckImportExcel")
    public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String filePath = System.getProperty("java.io.tmpdir") + File.separator + originalFilename;
            file.transferTo(new File(filePath));
            Result<?> result = stuCheckService.importExcel(filePath);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("数据导入失败");
        }
    }


}
